/*============================================================================
 PROJECT: Talklife
 FILE:    CDCIconButton.m
 AUTHOR:  Clark Kent
 DATE:    5/21/13
 =============================================================================*/

/*============================================================================
 IMPORT
 =============================================================================*/
#import "CDCIconButton.h"

/*============================================================================
 PRIVATE MACRO
 =============================================================================*/

#define kCDCButtonUpdateGUITime         0.075f

/*============================================================================
 PRIVATE INTERFACE
 =============================================================================*/

@interface CDCIconButton()

@end


@implementation CDCIconButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self createBaseUI];
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

#pragma mark - Over ride methods

- (void)awakeFromNib {
    [super awakeFromNib];
    [self setBackgroundColor:self.backgroundColor forState:UIControlStateNormal];
    [self createBaseUI];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    // Get bounds of view
    CGRect bounds = self.bounds;
    
    // Relayout icon
    CGRect iconFrame = _iconImageView.frame;
    
    // Set default icon is center
    iconFrame.size = _iconSize;
    iconFrame.origin.x = self.frame.size.width/2 - iconFrame.size.width/2;
    iconFrame.origin.y = (_iconTopMargin > 0 ? _iconTopMargin : (bounds.size.height - iconFrame.size.height)/2);
    _iconImageView.frame = iconFrame;
    
    // Set title default center
    CGRect titleFrame = _title.frame;
    titleFrame.origin.x = 0;
    //titleFrame.origin.y = (_titleTopMargin > 0 ? (_titleTopMargin + iconFrame.origin.y + iconFrame.size.height) : (iconFrame.origin.y + iconFrame.size.height));
    titleFrame.origin.y = _titleTopMargin + iconFrame.origin.y + iconFrame.size.height;
    titleFrame.size.width = bounds.size.width;
    titleFrame.size.height = bounds.size.height - _iconTopMargin - iconFrame.size.height - _titleTopMargin;
    _title.frame = titleFrame;
    
    [_title setTextAlignment:NSTextAlignmentCenter];
}

- (void)dealloc {
    _iconImage = nil;
    _iconImageView = nil;
    _title = nil;
}

#pragma mark - Implement methods

/*----------------------------------------------------------------------------
 Method:      createBaseUI   Create basic subviews
 -----------------------------------------------------------------------------*/

- (void)createBaseUI {
    _isRetinalIconImage = NO;
    
    // Create icon view
    _iconImageView = [[UIImageView alloc] init];
    _iconImageView.backgroundColor = [UIColor clearColor];
    [self addSubview:_iconImageView];
    
    // Create for title
    _title = [[UILabel alloc] init];
    _title.backgroundColor = [UIColor clearColor];
    [self addSubview:_title];
}

- (void)setIconImage:(UIImage *)iconImage forState:(UIControlState)state {
    if(iconImage == nil)
        return;
    
    if(_iconImageStates == nil) {
        _iconImageStates = [[NSMutableDictionary alloc] init];
    }
    
    _iconImageStates[[NSNumber numberWithInt:state]] = iconImage;
    
    if(_iconImageView.image == nil && iconImage != nil && self.state == state) {
        self.iconImage = iconImage;
    }
}

- (void)setIconImageWithUrl:(NSString *)imageUrl forState:(UIControlState)state {
    imageUrl = [imageUrl trim];
    
    if([imageUrl isEqualToString:@""]) {
        return;
    }

    UIImageView *imageViewTemp = [[UIImageView alloc] init];
    [imageViewTemp setImageWithURLString:imageUrl
                         placeholderImage:nil
                                  success:^(UIImage *image) {
                                      //_iconImageView.image = nil;
                                      [self setIconImage:image forState:state];
                                  }
                                  failure:^(NSError *error){
                                      NSLog(@"%@", error);
                                  }];
}

- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state {
    if (_backgroundColorStates == nil)
        _backgroundColorStates = [[NSMutableDictionary alloc] init];
    
    _backgroundColorStates[[NSNumber numberWithInt:state]] = backgroundColor;

    if (self.backgroundColor == nil || self.state == state)
        [self setBackgroundColor:backgroundColor];
}

- (void)setTextColor:(UIColor *)textColor forState:(UIControlState)state {
    if (_textColorStates == nil)
        _textColorStates = [[NSMutableDictionary alloc] init];
    
    _textColorStates[[NSNumber numberWithInt:state]] = textColor;
    
    if (self.textColor == nil || self.state == state)
        [self setTextColor:textColor];
}

- (void)showIndicatorView:(BOOL)status {
    if(!_indicatorView) {
        self.indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        _indicatorView.hidesWhenStopped = YES;
        [self addSubview:_indicatorView];
        
        /* layout frame */
        _indicatorView.center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
    }
    
    [_indicatorView bringSubviewToFront:self];
    
    if(status) {
        [_indicatorView startAnimating];
    } else {
        [_indicatorView stopAnimating];
    }
}

/*----------------------------------------------------------------------------
 Method:      setIconImage   Set new icon image and relayout it
 -----------------------------------------------------------------------------*/

- (void)setIconImage:(UIImage *)iconImage {
    if(_iconImageView && iconImage) {
        
        if(_isRetinalIconImage) {
            iconImage = [UIImage imageWithCGImage:[iconImage CGImage]
                                scale:(2.0)
                          orientation:(iconImage.imageOrientation)];
        }
        
        _iconImageView.image = iconImage;
        [self setIconSize:iconImage.size];
        [self setNeedsLayout];
    }
}

/*----------------------------------------------------------------------------
 Method:      setIconSize   Set new icon size
 -----------------------------------------------------------------------------*/

- (void)setIconSize:(CGSize)iconSize {
    _iconSize = iconSize;
    [self setNeedsLayout];
}

/*----------------------------------------------------------------------------
 Method:      setText   set content for button label;
 -----------------------------------------------------------------------------*/

- (void)setText:(NSString *)text {
    _title.text = text;
    [self setNeedsLayout];
}

/*----------------------------------------------------------------------------
 Method:      setTitleTopMargin   set top margin for title, relactive with icon
 -----------------------------------------------------------------------------*/

- (void)setTitleTopMargin:(float)titleTopMargin {
    _titleTopMargin = titleTopMargin;
    [self setNeedsLayout];
}

/*----------------------------------------------------------------------------
 Method:      setTextColor   set color for title
 -----------------------------------------------------------------------------*/

- (void)setTextColor:(UIColor *)textColor {
    _textColor = textColor;
    _title.textColor = _textColor;
}

/*----------------------------------------------------------------------------
 Method:      updateGUIWithState   Update icon view, background, textColor when input new state. Include animtions
 -----------------------------------------------------------------------------*/

- (void)updateGUIWithState:(UIControlState)state {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:kCDCButtonUpdateGUITime];
    
    // Get and set background color with state
    UIColor *backgroundColor = _backgroundColorStates[[NSNumber numberWithInt:state]];
    
    if(backgroundColor)
        self.backgroundColor = backgroundColor;
    
    // Get and set text color with state
    UIColor *textColor = _textColorStates[[NSNumber numberWithInt:state]];
    
    if(textColor) {
        _title.textColor = textColor;
    }
    
    // Get and set icon image with state
    UIImage *iconImage = _iconImageStates[[NSNumber numberWithInt:state]];
    
    if(iconImage)
        self.iconImage = iconImage;
    
    [UIView commitAnimations];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self updateGUIWithState:UIControlStateHighlighted];
    
    [super touchesBegan:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self updateGUIWithState:UIControlStateNormal];
    
    [super touchesEnded:touches withEvent:event];
}

- (void) touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [self updateGUIWithState:UIControlStateNormal];
    
	[super touchesCancelled:touches withEvent:event];
}

- (void)setSelected:(BOOL)selected {
    [super setSelected:selected];
    
    if(selected) {
        [self updateGUIWithState:UIControlStateSelected];
    } else {
        [self updateGUIWithState:UIControlStateNormal];
    }
}

- (void)setEnabled:(BOOL)enabled {
    [super setEnabled:enabled];
    
    if(enabled) {
        [self updateGUIWithState:UIControlStateNormal];
    } else {
        [self updateGUIWithState:UIControlStateDisabled];
    }
}

@end
